package com.dotakill.controller;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;

/**
 * 拦截请求页面的URL,检验Session是否过期
 *
 * @author houxg
 * @date 2017-4-18
 */
public class HandlerInterceptor extends HandlerInterceptorAdapter {// 此处一般继承HandlerInterceptorAdapter适配器即可

	/***
	 * 请求预处理
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		// 当前调试用,以后可删除
		//System.out.println("检测到请求：getServletPath：" + request.getServletPath() + ", getRequestURI：" + request.getRequestURI());
		System.out.println("检测到请求：getRequestURI：" + request.getRequestURI()); 
		HttpSession session = request.getSession(true);
		Object userSession = session.getAttribute("userLoginInfo");
		// 判断用户Session是否有效正常
		if (userSession != null) {
			return true;
		} else {
			if(request.getParameter("userName")!=null && !"".equals(request.getParameter("userName")))
			{
				String userName = request.getParameter("userName");
				String userId = request.getParameter("userId");
				//if(saveUserSession(userName,userId))
				return true;
			}
			String uri = request.getRequestURI();
			// 判断是否是来自Ajax请求
			if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
				response.setHeader("sessionstatus", "timeout");
			} else {
				String indexUrl = "";
				if ("".equals(request.getServletPath())) {
					indexUrl = request.getRequestURI() + "/login";
				} else {
					indexUrl = uri.substring(0, uri.indexOf("/", 1)) + "/login";
				}
				PrintWriter out = response.getWriter();
				StringBuilder builder = new StringBuilder();
				builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
				builder.append("if (top.location != self.location){");
				builder.append("window.top.location.href=\"" + indexUrl + "\";}");
				builder.append("else{");
				builder.append("location.href=\"" + indexUrl + "\";}"); /**/
				builder.append("</script>");
				out.print(builder.toString());
				out.close();
			}
			return false;
		}
		
	}
	
	/**
	 * 请求后处理
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		// System.out.println("=========== postHandle");
	}

	/**
	 * 请求完成后处理
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// System.out.println("=========== afterCompletion");
	}
}
